package models;

import java.util.ArrayList;
import java.util.List;

import helpers.GeneralHelper;

import javax.cache.Cache;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.Webmail;

public class WebmailModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "webmail_";
	
	private static WebmailModel instance = null;
	
	public static WebmailModel getInstance() {
		if (instance == null) {
			instance = new WebmailModel();
		}
		
		return instance;
	}
	
	private WebmailModel() {
		try {
			ObjectifyService.register(Webmail.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<Webmail> list(int page, int limit) {
		List<Webmail> webmails = new ArrayList<Webmail>();
		
		int start = (page - 1) * limit;
		webmails = ofy.query(Webmail.class).limit(limit).offset(start).list();
		
		return webmails;
	}
	
	public Webmail get(String id) {
		Webmail webmail = new Webmail();
		
		try {
			webmail = ofy.get(new Key<Webmail>(Webmail.class, id));
		} catch (Exception e) {
			webmail = null;
		}
		
		return webmail;
	}
	
	public void insert(Webmail webmail) {
		ofy.put(webmail);
	}
	
	public void delete(Webmail webmail) {
		ofy.delete(webmail);
	}
	
	public Webmail getWatting() {
		Webmail webmail = new Webmail();
		try {
			webmail = ofy.query(Webmail.class).filter("status", 1).get();
		} catch (Exception e) {
			webmail = null;
		}
		
		return webmail;
	}
}
